package com.example.authservice.tool;

import com.example.common.entity.OpenApiApp;
import com.example.common.utils.SnowFlakeUtil;
import com.example.common.utils.WillingAESUtils;
import lombok.SneakyThrows;

import static com.example.common.utils.WillingAESUtils.digest;

/**
 * @author sunyong
 * @date 2021/8/18
 */
public class OpenApiAppTools {
    protected final static String PREFIX = "wloa";

    /**
     * 初始化一个开放平台的应用
     *
     * @param email
     * @param appId
     * @param secret
     * @return
     */
    // TODO 自定义解析异常
    @SneakyThrows
    public static OpenApiApp initOpenApiApp(String email, String appId, String secret) {
        OpenApiApp openApiApp = new OpenApiApp();
        openApiApp.setId(SnowFlakeUtil.nextId());
        openApiApp.setAppId(appId);
        openApiApp.setAppSecret(WillingAESUtils.encrypt(secret));
        openApiApp.setEmail(email);
        return openApiApp;
    }

    /**
     * 生成开放平台自建应用的appId
     * 方法：tenant+curTime计算MD5
     *
     * @param email
     * @return
     */
    public static String calculateAppId(String email) {
        if (email == null) {
            return null;
        }
        String curTime = String.valueOf(System.currentTimeMillis());
        return PREFIX + digest(email + curTime, "MD5");
    }

    /**
     * 生成secret
     * 方法：tenantId+appId计算SHA-256
     *
     * @param email
     * @param appId
     * @return
     */
    public static String calculateSecret(String email, String appId) {
        return digest(email + appId, "SHA-256");
    }
}
